import { loadEnv } from "vite";
import type { UserConfig, ConfigEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import { fileURLToPath, URL } from "node:url";
import progress from "vite-plugin-progress";
import viteCompression from "vite-plugin-compression";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import legacy from "@vitejs/plugin-legacy";

// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfig => {
  const env = loadEnv(mode, process.cwd());
  return {
    plugins: [
      vue(),
      Components({
        include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/, /\.md$/],
        resolvers: [
          (componentName) => {
            if (componentName.startsWith("Icon")) {
              return {
                name: componentName.slice(4),
                from: "@icon-park/vue-next",
              };
            }
          },
        ],
        dts: "src/types/components.d.ts",
      }),
      AutoImport({
        include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/, /\.md$/],
        imports: [
          // 插件预设支持导入的api
          "vue",
          "vue-router",
          "pinia",
          // 自定义导入的api
        ],
        resolvers: [],
        dts: "src/types/auto-imports.d.ts",
      }),
      progress(),
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: "gzip",
        ext: ".gz",
        deleteOriginFile: false,
      }),
      legacy({
        targets: ["defaults", "ie >= 11", "chrome 52"], //需要兼容的目标列表，可以设置多个
        additionalLegacyPolyfills: ["regenerator-runtime/runtime"],
        renderLegacyChunks: true,
        polyfills: [
          "es.symbol",
          "es.array.filter",
          "es.promise",
          "es.promise.finally",
          "es/map",
          "es/set",
          "es.array.for-each",
          "es.object.define-properties",
          "es.object.define-property",
          "es.object.get-own-property-descriptor",
          "es.object.get-own-property-descriptors",
          "es.object.keys",
          "es.object.to-string",
          "web.dom-collections.for-each",
          "esnext.global-this",
          "esnext.string.match-all",
        ],
      }),
    ],
    resolve: {
      extensions: [".js", ".ts", ".tsx", ".jsx"],
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    // base: "/ningxiang-datav",
    base: "./",
    server: {
      host: "0.0.0.0",
      port: 8082,
      open: false,
      headers: {
        "Access-Control-Allow-Origin": "*",
      },
      hmr: {
        overlay: false,
      },
      proxy: {
        "/ningxiang": {
          target: env.VITE_PROXY_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/ningxiang/, ""),
        },
        "/timebank": {
          target: "https://mzj.nanjing.gov.cn/nxyl/sjyh/api/timebank/jd_data",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/timebank/, ""),
        },
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/styles/scss/variables.scss" as *;`,
          charset: false,
        },
      },
    },
    build: {
      chunkSizeWarningLimit: 500,
      rollupOptions: {
        output: {
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
          experimentalMinChunkSize: 10 * 1024,
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return id
                .toString()
                .split("node_modules/")[1]
                .split("/")[0]
                .toString();
            }
          },
        },
      },
    },
  };
};
